package archer.framework.common.repository.support.ebean.page;

import archer.framework.common.repository.page.PageConverter;
import archer.framework.common.repository.page.PageInfo;
import archer.framework.core.exception.BaseException;
import archer.framework.utils.ValidateUtils;
import com.avaje.ebeaninternal.server.query.LimitOffsetPagedList;

/**
 * Ebean分页转换器
 */
public class EbeanPageConverter implements PageConverter {

    @Override
    public PageInfo convert(Object page) {

        PageInfo result = new PageInfo();

        if (ValidateUtils.isEmpty(page)) {
            return result;
        }

        if (!(page instanceof LimitOffsetPagedList)) {
            throw new BaseException("unsupported page source");
        }

        LimitOffsetPagedList pagedList = (LimitOffsetPagedList) page;

        String display = pagedList.getDisplayXtoYofZ(",", ",");
        int first = Integer.valueOf(display.split(",")[0]);
        int pageIndex = first / pagedList.getPageSize();
        return result.setPageIndex(pageIndex + 1)
                .setHasNext(pagedList.hasNext())
                .setHasPrev(pagedList.hasPrev())
                .setPageSize(pagedList.getPageSize())
                .setTotal(pagedList.getTotalRowCount())
                .setPages(pagedList.getTotalPageCount())
                .setRows(pagedList.getList())
                .setStartRow(ValidateUtils.isEmpty(result.getRows()) ? 0 : first)
                .setEndRow(result.getStartRow() + (ValidateUtils.isEmpty(result.getRows()) ? 0 : result.getRows().size() - 1));
    }

    private static EbeanPageConverter instance = null;

    private EbeanPageConverter() {
    }

    public static PageConverter instance() {
        if (instance == null) {
            instance = new EbeanPageConverter();
        }
        return instance;
    }
}